<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑优惠券' : '新增优惠券'"
    width="600px"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="优惠券名称" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入优惠券名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="优惠券描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入优惠券描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="优惠券类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择优惠券类型" style="width: 100%">
          <el-option
            v-for="item in couponTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优惠金额" prop="amount">
        <el-input-number
          v-model="form.amount"
          :min="0.01"
          :max="9999.99"
          :precision="2"
          :step="0.01"
          style="width: 100%"
        />
        <span class="form-tip">
          {{ form.type === 1 ? '单位：元' : form.type === 2 ? '单位：%' : '' }}
        </span>
      </el-form-item>

      <el-form-item label="最低消费" prop="minSpend">
        <el-input-number
          v-model="form.minSpend"
          :min="0"
          :max="99999.99"
          :precision="2"
          :step="0.01"
          style="width: 100%"
          placeholder="0表示无限制"
        />
        <span class="form-tip">单位：元，0表示无限制</span>
      </el-form-item>

      <!-- 时间设置 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <div class="form-tip">
              <el-icon><Clock /></el-icon>
              优惠券生效开始时间
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <div class="form-tip">
              <el-icon><Clock /></el-icon>
              优惠券失效时间
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 有效期设置 -->
      <el-form-item label="有效期时长" prop="validHours">
        <el-input-number
          v-model="form.validHours"
          :min="1"
          :max="8760"
          :step="1"
          style="width: 200px"
          placeholder="请输入有效期"
        />
        <span class="form-tip">
          <el-icon><Timer /></el-icon>
          单位：小时
        </span>
      </el-form-item>



      <el-form-item label="发放数量" prop="totalCount">
        <el-input-number
          v-model="form.totalCount"
          :min="1"
          :max="10000"
          style="width: 100%"
        />
        <span class="form-tip">最多10000张</span>
      </el-form-item>

      <el-form-item label="每人限领" prop="limitPerUser">
        <el-input-number
          v-model="form.limitPerUser"
          :min="1"
          :max="100"
          style="width: 100%"
        />
        <span class="form-tip">每人最多可领取的数量</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Clock, Timer } from '@element-plus/icons-vue'
import { createCoupon, updateCoupon, couponTypeOptions } from '@/api/coupon'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const loading = ref(false)

// 表单数据
const form = reactive({
  title: '',
  description: '',
  type: null,
  amount: null,
  minSpend: 0,
  startTime: '',
  endTime: '',
  validHours: null,
  totalCount: null,
  limitPerUser: 1
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入优惠金额', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 9999.99, message: '金额范围 0.01-9999.99', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.startTime && new Date(value) <= new Date(form.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  validHours: [
    { required: true, message: '请输入有效期时长', trigger: 'blur' },
    { type: 'number', min: 1, max: 8760, message: '时长范围 1-8760 小时', trigger: 'blur' }
  ],
  totalCount: [
    { type: 'number', min: 1, max: 10000, message: '数量范围 1-10000', trigger: 'blur' }
  ],
  limitPerUser: [
    { type: 'number', min: 1, max: 100, message: '数量范围 1-100', trigger: 'blur' }
  ]
})

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(form, newData)
  }
}, { immediate: true, deep: true })

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible && !props.isEdit) {
    // 新增时重置表单
    resetForm()
    // 设置默认时间和有效期
    setDefaultValues()
  }
})

// 设置默认值
const setDefaultValues = () => {
  // 设置默认时间（当前时间到30天后）
  const now = new Date()
  const endTime = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000) // 30天后

  form.startTime = now.toISOString().slice(0, 19).replace('T', ' ')
  form.endTime = endTime.toISOString().slice(0, 19).replace('T', ' ')

  // 设置默认有效期（7天 = 168小时）
  form.validHours = 168
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined, // 清除id字段
    title: '',
    description: '',
    type: null,
    amount: null,
    minSpend: 0,
    startTime: '',
    endTime: '',
    validHours: null,
    totalCount: null,
    limitPerUser: 1
  })

  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    // 构建提交数据
    const submitData = { ...form }

    // 创建时排除id字段
    if (!props.isEdit) {
      delete submitData.id
    }

    // 验证时间
    if (new Date(submitData.endTime) <= new Date(submitData.startTime)) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    if (props.isEdit) {
      await updateCoupon(form.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createCoupon(submitData)
      ElMessage.success('创建成功')
    }
    
    emit('success')
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}


// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}
</script>

<style scoped>
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-radio-group {
  width: 100%;
}

.el-radio {
  margin-right: 30px;
}

/* 美化时间选择器 */
.el-date-picker {
  width: 100%;
}

/* 美化数字输入框 */
.el-input-number {
  width: 100%;
}

/* 美化单选按钮组 */
.el-radio-group .el-radio {
  color: #606266;
  font-weight: 500;
}

.el-radio-group .el-radio.is-checked {
  color: #409eff;
}

/* 表单项标签样式 */
.el-form-item__label {
  font-weight: 500;
  color: #303133;
}

/* 对话框标题样式 */
:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 按钮样式 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>

<style scoped>
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}
</style>
